<?php
/*
          U1,
          LMF1Yr,
          BOOMBBBBBBq
         7BEP0PNqZBM
         B8kPFXFX0B
        YBXXSSFkSB;     APUXIN
        Bqk1k5SFNZ      Web OS
     :r0Ek5kSXSXO;
   jBBBNPkXF5uUYF:      by Apuxin Team
  BBqPkXUj7rrr;rrur
.J8FX5u7r;rr7r7r7rUi    kernel.php: Main kernel file. Loads kernel modules
0UkkJ7irr7rrr7rrrrrj
PuX7;i7;r;r;rrririrL.
 7L;;rrrrriri;i;i;iL
  YL7;riri;i;iii;iL:
   ;LLrr;ri;i;irr7.
       ...... .

*/

/**
*
*/

// ERROR TYPES
define("FATAL_ERROR", 4000);
define("AUTH_ERROR", 3000);
define("WARNING", 2000);
define("NOTICE", 1000);

/**
 * Returns a language string
 * @param String $stringkey Key for the Language String
 * @param String $var Variable which can be replaced in a string
 * @return String
 */
function __($stringkey, $var = "")
{
	// Sprachdateien auslesen
	$dir = opendir("languages/" . LANGUAGE);
	while($file = readdir($dir))
	{
		if(preg_match("|(.*?).lng.php|i", $file))
		{
			include_once "languages/" . LANGUAGE . "/" . $file;
		}
	}

	return $_LANG[$stringkey];
}

class APUXIN_SERVICE
{
  private $apuxin_service_info;
  public $apuxin_service_info_object = true;

  function __construct()
  {
    $this->apuxin_service_info = array(
      'name' => "service",
      'desc' => "Description of the service",
      'version' => 0.1,
      'onlyOnce' => false
    );
  }

  protected function info_setName($name) {$this->apuxin_service_info['name'] = $name;}
  protected function info_setDesc($desc) {$this->apuxin_service_info['desc'] = $desc;}
  protected function info_setVersion($version) {$this->apuxin_service_info['version'] = $version;}
  protected function info_setOnlyOnce($oo){$this->apuxin_service_info['onlyOnce'] = $oo;}

  public function info_getName() {return $this->apuxin_service_info['name'];}
  public function info_getDesc() {return $this->apuxin_service_info['desc'];}
  public function info_getVersion() {return $this->apuxin_service_info['version'];}
  public function info_getOnlyOnce() {return $this->apuxin_service_info['onlyOnce'];}
}

/**
* calls a service
*
* @param string $name The name of the service
* @param string $function The function to be called
* @param array $param Holds the Parameters for the function
*/
$apuxin_core_services = array();
function load_service($name, $param = array()/*, $function, $param = array()*/)
{
  global $apuxin_core_services;
  if(isset($apuxin_core_services[$name])) return $apuxin_core_services[$name];
	$file = dirname(__FILE__).DS."..".DS."services".DS.$name.".service.php";
    if(file_exists($file))
    {
        include_once($file);
        if(class_exists($name))
        {
            $inst = new $name();
            if(count($param)>0) {call_user_method_array("initialize", $inst, $param);}
            //foreach($inst as $key => $value) echo "$key => $value <br>";
            if(property_exists($inst, "apuxin_service_info_object")) {
              if($inst->info_getOnlyOnce()) {
                $apuxin_core_services[$name] = $inst;
              }
            }
        } else
        {
            throw_error("Kernel - Service - ".$name." existiert nicht!", FATAL_ERROR);
        }
    } else
    {
        throw_error("Kernel - Service - " . $name . " existiert nicht!", FATAL_ERROR);
    }
    return $inst;
}

/**
* throws an error - sollte vielleicht dringend mal überarbeitet werden!
*
* @param string $message The message to be logged
* @param int $type of the error. Default is FATAL_ERROR
*/
function throw_error($message, $type=FATAL_ERROR)
{
    global $output;

	if($type == FATAL_ERROR)
	{
		logit("FATAL_ERROR: " . $message);
        $output->add("<strong>FATAL_ERROR:</strong> ".$message);
        $output->flush();
		die();
	} elseif($type == AUTH_ERROR)
	{
		logit("AUTH_ERROR: " . $message);
        $output->add("<strong>AUTH_ERROR:</strong> ".$message);
	} elseif($type == WARNING)
	{
		logit("WARNING: " . $message);
        $output->add("<strong>WARNING:</strong> ".$message);
	} elseif($type == NOTICE)
	{
		logit("NOTICE: " . $message);
        $output->add("<strong>NOTICE:</strong> ".$message);
	}
}

class APUXIN_EasyFileHandler
{
  private $pointer;
  function __construct($filename)
  {
    $this->pointer = fopen($filename, "a");
  }
  function add($msg)
  {
    fputs($this->pointer, "\r\n" . $msg);
  }
  function __destruct()
  {
    fclose($this->pointer);
  }
}

/**
* logs a message in the error.log
*
* @param string $message The message to be logged
*/
$apuxin_core_logit = "";

function logit($msg)
{
  global $apuxin_core_logit;
  if(!is_object($apuxin_core_logit)) {
    $apuxin_core_logit = new APUXIN_EasyFileHandler(dirname(__FILE__) . DS . "error.log");
  }
  $apuxin_core_logit->add($msg);
}


// UI starten
// Später Überprüfung einbauen, ob App laden, Login oder Desktop!!!!

// Aber zuerst Session starten...
$session = load_service("sessions");
//$vfs = load_service("vfs");
$session->startSession();

// Dann Outputbuffer laden...
$output = load_service("outputbuffer");

/**
 * Logs an user in
 * @param array $data Contains the username and the password
 */
function login($data)
{
    $output = load_service("outputbuffer");

    $user = load_service("user");
    if(!isset($_SESSION["rights"]) || empty($_SESSION['rights']))
    {
        if($user->dologin($data['user'], $data['pw']))
        {
            $output->add("{'success':'1','username':'" . $user->getusername() . "','rights':'" . $user->getrights() . "'}");
        } else
        {
            $output->add("{'success':'0'}");
        }
    } else
    {
        // User ist bereits eingeloggt, loggt sich aber neu ein.
        // Hier sollte später am besten ein Fehler kommen, da er sich ja ansonsten doppelt einloggen könnte.
        // Zum Testen, andere Meldung würde mit der Zeit nerven :P
        $output->add("{'success':'1','username':'" . $user->getusername() . "','rights':'" . $user->getrights() . "'}");
    }
}

/**
 * Checks if the User is online
 */
function isonline()
{
    $output = load_service("outputbuffer");

    if(isset($_SESSION['rights']) && is_numeric($_SESSION['rights']) && $_SESSION['rights'] > 0)
    {
        $output->add("1");
    } else
    {
        $output->add("0");
    }
}

/**
 * Fetchs the user data like Username and Rights
 */
function getuserdata()
{
    $output = load_service("outputbuffer");
    
    $user = load_service("user");
    $output->add("{'username':'" . $user->getusername() . "','rights':'" . $user->getrights() . "'}");
}

/**
 * Displays the default HTML Template
 */
function defaultfunc()
{
    $output = load_service("outputbuffer");
    
    $template = <<<TEMPLATE
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="de" xml:lang="de">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
        <title>apuxin - Not logged in</title>
        <script type="text/javascript" src="js/mootoolscore.js"></script>
        <script type="text/javascript" src="js/mootoolsmore.js"></script>
        <script type="text/javascript" src="js/bootloader.js" id="bootloader"></script>
        <link rel="stylesheet" href="themes/standard/login.css" media="screen" id="boot" />
    </head>
    <body>
        <noscript><p>Um apuxin nutzen zu können, müssen Sie JavaScript aktivieren!</p></noscript>
    </body>
</html>
TEMPLATE;

    $output->add($template);
}

$req = load_service("requesthandler");

$req->addHandler("login", "login");
$req->addHandler("isonline", "isonline");
$req->addHandler("getuserdata", "getuserdata");

$req->setDefault("defaultfunc");

$req->handle();

// Flush!
$output->flush();

// Zum Testen ersteinmal alle Einloggdaten l�schen um beim Aktualisieren der
// Seite wieder die Loginbox zu zeigen.
//$session->clear();
?>
